package com.by.yz.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.by.yz.App;
import com.by.yz.R;
import com.by.yz.activity.regitser.RegisterActivity;
import com.by.yz.activity.regitser.RegisterInfoNextActivity;
import com.by.yz.chatuidemo.DemoHelper;
import com.by.yz.common.MFGT;
import com.by.yz.loginUtil.AccountRESTFul;
import com.by.yz.loginUtil.LoginRESTFul;
import com.by.yz.mypersonal.RevisePassword;
import com.by.yz.welcome.FirstWelcomeActivity;
import com.by.yz.welcome.WelcomeActivity;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;

import org.json.JSONObject;

/**
 * A login screen that offers login via email/password.
 */
public class LoginActivity extends AppCompatActivity{
    private App application;
    private Button resister;
    private Button login;
    private EditText account;
    private EditText password;
    private Button seePassword;
    private TextView forgetPassword;
    private String phoneNumber;
    private String passWord;
    private boolean progressShow;
    private Boolean showPassword = true;

    private static final int GO_LOGIN = 100;
    private static final int GO_GUIDE = 200;

    protected void onCreate( Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        application = (App)getApplication();
        application.addActivity(this);
        setContentView(R.layout.activity_login);
        final  Intent intent=new Intent();

        //注册操作
        resister = (Button) findViewById(R.id.register);
        resister.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                intent.setClass(LoginActivity.this, RegisterActivity.class);
                startActivity(intent);
//                Handler handler = new Handler();
//                handler.postDelayed(new Runnable() {
//                    public void run() {
//                        MFGT.finish(LoginActivity.this);
//                    }
//                },2000);
            }
        });

        //登陆操作
        account=(EditText) findViewById(R.id.account);
        password=(EditText)findViewById(R.id.password);
        login = (Button) findViewById(R.id.login);
        login.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                phoneNumber=account.getText().toString();
                passWord=password.getText().toString();
                if(phoneNumber.equals("") || passWord.equals("")) {

                    final MaterialDialog registerSuccess = new MaterialDialog.Builder(LoginActivity.this)
                            .content("手机号或密码不能为空，请重新输入")
                            .show();
                    Handler handler = new Handler();
                    handler.postDelayed(new Runnable() {
                        public void run() {
                            registerSuccess.dismiss();//设置弹框消失
                        }
                    }, 1000);

                    return;
                }
                //判断是否有网络
                if (isNetworkAvailable(LoginActivity.this)) {

                    AccountRESTFul accountRESTFul=new AccountRESTFul();//申请权限，返回一 个隐形的JSONObject对象
                    accountRESTFul.get(new AccountRESTFul.IhttpCb() {
                        @Override
                        public void ok(JSONObject response) {
                            LoginRESTFul loginRESTFul = new LoginRESTFul();
                            loginRESTFul.login(passWord, phoneNumber, new LoginRESTFul.ILoginCb() {
                                @Override
                                public void ok(String response) {
                                    AccountRESTFul account=new AccountRESTFul();//更新权限，得到一个真实的令牌
                                    account.get(new AccountRESTFul.IhttpCb() {
                                        @Override
                                        public void ok(JSONObject response) {

                                            progressShow = true;
                                            final ProgressDialog pd = new ProgressDialog(LoginActivity.this);
                                            pd.setCanceledOnTouchOutside(false);
                                            pd.setOnCancelListener(new DialogInterface.OnCancelListener() {
                                                @Override
                                                public void onCancel(DialogInterface dialog) {
                                                    Log.d("666", "EMClient.getInstance().onCancel");
                                                    progressShow = false;
                                                }
                                            });
                                            pd.setMessage(getString(R.string.Is_landing));
                                            pd.show();
                                            EMClient.getInstance().login(phoneNumber,passWord, new EMCallBack() {

                                                @Override
                                                public void onSuccess() {
                                                    Log.d("logononon", "login: onSuccess");

                                                    // ** manually load all local groups and conversation
                                                    EMClient.getInstance().groupManager().loadAllGroups();
                                                    EMClient.getInstance().chatManager().loadAllConversations();
                                                    // update current user's display name for APNs
                                                    boolean updatenick = EMClient.getInstance().updateCurrentUserNick(
                                                            "");
                                                    if (!updatenick) {
                                                        Log.e("LoginActivity", "update current user nick fail");
                                                    }
                                                    if (!LoginActivity.this.isFinishing() && pd.isShowing()) {
                                                        pd.dismiss();
                                                    }
                                                    // get user's info (this should be get from App's server or 3rd party service)
                                                    DemoHelper.getInstance().getUserProfileManager().asyncGetCurrentUserInfo();

                                                }

                                                @Override
                                                public void onProgress(int progress, String status) {
                                                    Log.d("logononon", "login: onProgress");
                                                }

                                                @Override
                                                public void onError(final int code, final String message) {
                                                    Log.d("loginininin", "login: onError: " + code);
                                                    if (!progressShow) {
                                                        return;
                                                    }
                                                    runOnUiThread(new Runnable() {
                                                        public void run() {
                                                            pd.dismiss();
                                                            Toast.makeText(getApplicationContext(), getString(R.string.Login_failed) + message,
                                                                    Toast.LENGTH_SHORT).show();
                                                        }
                                                    });
                                                }
                                            });

                                            /*更新Token*/
                                            String[] UserData=new String[3];
                                            UserData[0]=phoneNumber;
                                            UserData[1]=passWord;
                                            //设置Cookie，进行账号登陆缓存
                                            App.setCacheUser(LoginActivity.this,UserData);
                                            //用户登录，写入用户缓存
                                            App.cacheUserToken(LoginActivity.this);
                                            /*更新Token完毕*/
                                            Toast.makeText(getApplicationContext(), "登陆成功", Toast.LENGTH_SHORT).show();
                                            intent.setClass(LoginActivity.this, MainActivity.class);
                                            startActivity(intent);
                                            //finish();
                                            Handler handler = new Handler();
                                            handler.postDelayed(new Runnable() {
                                                public void run() {
                                                    MFGT.finish(LoginActivity.this);
                                                }
                                            },3000);
                                        }

                                        @Override
                                        public void error(String error) {
                                            Log.e("AccountRESTFul-2-Error",error);
                                        }
                                    });
                                }

                                @Override
                                public void error(String error) {
                                    Log.e("LoginRESTFul-Error", error);
                                    final MaterialDialog registerSuccess = new MaterialDialog.Builder(LoginActivity.this)
                                            .content("登陆失败,请检查手机号码和密码是否正确")
                                            .show();
                                    Handler handler = new Handler();
                                    handler.postDelayed(new Runnable() {
                                        public void run() {
                                            registerSuccess.dismiss();//设置弹框消失
                                        }
                                    }, 1000);
                                }
                            });
                        }
                        @Override
                        public void error(String error) {
                            Log.e("AccountRESTFul-1-Error",error);
                        }
                    });

                }else{
                    //无网络连接情况
                    new AlertDialog.Builder(LoginActivity.this)
                            .setTitle("提示!")
                            .setIcon(android.R.drawable.ic_dialog_info)
                            .setMessage("检测到您还没开启网络，请开启")
                            .setNegativeButton("取消", null)
                            .setPositiveButton("开启",
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog,
                                                            int which) {
                                            startActivity(new Intent(
                                                    Settings.ACTION_WIRELESS_SETTINGS));// 进入无线网络配置界面
                                        }
                                    }).show();
                }
            }
        });

        //忘记密码操作
        forgetPassword=(TextView) findViewById(R.id.forgetPassword);
        forgetPassword.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                intent.setClass(LoginActivity.this, RevisePassword.class);
                intent.putExtra("myPhone", "");
                startActivity(intent);
            }
        });

        //查看密码
        seePassword = (Button) findViewById(R.id.see_password);
        seePassword.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if(showPassword){//显示密码
                    showPassword = !showPassword;
                    seePassword.setBackgroundResource(R.mipmap.eye);
                    password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    password.setSelection(password.getText().toString().length());
                }else{//隐藏密码
                    showPassword = !showPassword;
                    seePassword.setBackgroundResource(R.mipmap.eye1);
                    password.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    password.setSelection(password.getText().toString().length());
                }
            }
        });
    }

    /*
     * 判断是否有网络
     */
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm == null) {
            return false;
        } else {
            // 如果仅仅是用来判断网络连接　　　　　　
            // 则可以使用 cm.getActiveNetworkInfo().isAvailable();
            NetworkInfo networkInfo = cm.getActiveNetworkInfo();
            if (networkInfo != null) {
                Log.e("hj","isNetworkAvailable - 是否有网络： "+ networkInfo.isAvailable());
                return true;
            } else {
                Log.e("hj", "isNetworkAvailable - 完全没有网络！");
                return false;
            }
        }
    }
}
